package com.cudex.negocio.daos;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;

import com.cudex.negocio.beans.TipoRubro;



/**
 * @author Nicolas Bordenave
 * @date 22/11/2011
 * @version 1.0
 */
@Stateless
public class TipoRubroDAO implements ITipoRubroDAO {

	private static final long serialVersionUID = 3799643488107864542L;

	private static final Logger log = Logger.getLogger(TipoRubroDAO.class
			.getName());

	@PersistenceContext(unitName = "JPA_UNIT_CUDEX")
	EntityManager em;

	@Override
	public Boolean salvarTipo(TipoRubro tpo) throws Exception {
		// TODO Auto-generated method stub

		Boolean result = false;
		try {
			em.persist(tpo);
			result = true;
		} catch (ConstraintViolationException e) {
			// log.error("salvarTipo : ConstraintViolationException");
			throw e;
		} catch (PersistenceException e) {
			// log.error("salvarTipo : PersistenceException");
			throw e;
		} catch (Exception e) {
			throw e;
		}
		return result;
	}

	@Override
	public TipoRubro modificarTipo(TipoRubro tpo) throws Exception {
		TipoRubro objTmp = null;
		try {
			objTmp = em.merge(tpo);
			em.flush();

		} catch (ConstraintViolationException e) {
			// log.error("modificarTipo : ConstraintViolationException");
			throw e;
		} catch (PersistenceException e) {
			// log.error("modificarTipo : PersistenceException");
			throw e;
		} catch (Exception e) {
			throw e;
		}
		return objTmp;
	}

	@Override
	public TipoRubro buscarTipoRubro(String nombre)
			throws Exception {
		try {
			TipoRubro objTmp = (TipoRubro) em
					.createNativeQuery("buscarTipoRubrosPorNombre", TipoRubro.class)
					.setParameter("nombre", nombre).getSingleResult();
			return objTmp;
		} catch (Exception e) {
			log.error(e.getCause());
			// e.printStackTrace();
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TipoRubro> buscarTiposRubros() throws Exception {
		List<TipoRubro> result = null;
		try {
			result = (List<TipoRubro>) em.createNamedQuery("buscarTipoRubro")
					.getResultList();
			log.info("Count Rubros : " + result.size());
		} catch (Exception e) {
			log.error(e.getCause());
			// e.printStackTrace();
			throw e;
		}
		return result;
	}

}
